<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Potevio集成平台</title>
</head>
<body>
<div th:fragment="main" id="userControl" class="container userControl">
    <link rel="stylesheet" th:href="@{/css/organizationGroup/zTree/zTreeStyle/awesome.css}">
    <link rel="stylesheet" th:href="@{/css/userGroup/userControl.css}">
    <link rel="stylesheet" th:href="@{/assets/jqGrid/css/jqgridReset.css}">
    <div class="row">
        <div class="col-xs-3 userControlTree">
            <div class="userControl-content">
                <div class="userControl-title"><i class="iconfont">&#xe60a;</i>用户管理</div>
                <div class="userControl-tree">
                    <ul id="organizationTree" class="ztree"></ul>
                </div>
            </div>
        </div>
        <div class="col-xs-9 operation">
            <div class="operation-content">
                <div class="operation-header clearfix">
                    <form class="navbar-form" onsubmit="return false;">
                        <div class="groups form-group">
                                <span class="find">
                                    <i class="fa fa-search"></i>
                                </span>
                            <input type="text" class="form-control search" id="search" placeholder="请输入用户登录名"
                                   maxlength="25">
                        </div>
                        <input type="button" value="搜索" class="btn btn-primary nav-btn" id="searchUser">
                    </form>
                    <a href="#platform-userGroup-addUser" id="addUser" class="addUser btn btn-primary nav-btn"
                       th:if="${#authorization.expression('hasAuthority(''createUser'')')}">新建用户</a>
                </div>
                <div class="operation-table" id="operation-table">
                    <table id="userList"></table>
                    <div id="gridpager"></div>
                </div>
            </div>
        </div>
    </div>
    <!--删除提示模态框  -->
    <div id="deleteNotice" class="modal fade bs-example-modal-sm notice" tabindex="-1" role="dialog"
         aria-labelledby="mySmallModalLabel">
        <div class="modal-dialog modal-sm" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h3 class="modal-title" id="myModalLabel">操作提示</h3>
                </div>
                <div class="modal-body">
                    确认删除此条数据吗？
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" id="deleteData">确定</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                </div>
            </div>
        </div>
        <script th:src="@{/assets/jqGrid/js/jquery.jqGrid.src.js}"></script>
        <script th:src="@{/assets/jqGrid/js/grid.locale-cn.js}"></script>
        <script th:inline="javascript">
            // 权限控制
            var hasQueryUser = [[${#authorization.expression('hasAuthority(''queryUser'')')}]];
            var hasModifyUser = [[${#authorization.expression('hasAuthority(''modifyUser'')')}]];
            var hasDeleteUser = [[${#authorization.expression('hasAuthority(''deleteUser'')')}]];
            // jqgrid表格配置
            // 使jqgrid的宽和高自适应父元素
            var parentHeight, parentWidth;
            $(function () {
                //页面加载完成之后执行
                parentHeight = $("#operation-table").height() - 88,
                    parentWidth = $("#operation-table").width() + 14;
                pageInit();
            });

            // 初始化jqGrid
            // 操作按钮
            function operation(cellvalue, options, rowObject) {
                var amend = "";
                var deleted = "";
                if (hasModifyUser) {
                    amend = "<input class='btn btn-primary btn-xs modify' type='button' value='修改'>&nbsp;";
                }
                if (hasDeleteUser && rowObject.username !== 'admin') {
                    deleted = "<input class='btn btn-danger btn-xs del' type='button' value='删除' title='删除' data-toggle='modal' data-target='.bs-example-modal-sm'>";
                }
                return amend + deleted;
            };

            function connected(cellvalue, options, rowObject) {
                var connected = '';
                if (hasModifyUser) {
                    connected = "<input class='btn btn-primary btn-xs connected' type='button' value='关联用户'>";
                }
                return connected;
            };

            // 用户角色显示
            function auth(authType) {
                if (authType == 1) {
                    return '系统管理员';
                } else if (authType == 2) {
                    return '区域管理员';
                } else if (authType == 3) {
                    return '普通用户';
                }
            }

            function rolesId(array) {
                var newArray = [];
                for (var i = 0, len = array.length; i < len; i++) {
                    newArray[i] = array[i].id;
                }
                return newArray;
            }

            function pageInit() {
                //创建jqGrid组件
                jQuery("#userList").jqGrid({
                    url: contextPath + "/user/queryUserJqg",
                    datatype: "json",
                    height: parentHeight,
                    width: parentWidth,
                    colNames: ['用户ID', '登录名称', '登录密码', '用户名称', '用户类型', '用户类型ID', '角色类型', '角色ID', '用户头衔', '所属组织机构', '所属组织机构ID', '所属组织机构内部编码', '操作', '关联子系统用户'],
                    colModel: [
                        {name: 'id', index: 'id', sorttype: "int", hidden: true},
                        {name: 'username', index: 'username'},
                        {name: 'password', index: 'password', sorttype: "string", hidden: true},
                        {name: 'displayName', index: 'displayName', sorttype: "string"},
                        {name: 'authType', index: 'authName', sorttype: "string", formatter: auth, hidden: true},
                        {name: 'authType', index: 'authType', sorttype: "string", hidden: true},
                        {name: 'rolesName', index: 'rolesName', sorttype: "string"},
                        {name: 'roles', index: 'roles', sorttype: "string", formatter: rolesId, hidden: true},
                        {name: 'title', index: 'title', sorttype: "string", hidden: true},
                        {name: 'organizationName', index: 'organizationName', sorttype: "string"},
                        {name: 'organizationId', index: 'organizationId', sorttype: "string", hidden: true},
                        {name: 'organizationCode', index: 'organizationCode', sorttype: "string", hidden: true},
                        {
                            name: 'operation',
                            index: 'id',
                            sortable: false,
                            formatter: operation,
                            width: 180,
                            align: "center"
                        },
                        {
                            name: 'connected',
                            index: 'id',
                            sortable: false,
                            formatter: connected,
                            align: "center",
                            hidden: true
                        }
                    ],
                    sortname: 'id',
                    sortorder: 'asc',
                    viewrecords: true,
                    /* multiselect: true, */
                    rowNum: 20,
                    rowList: [20, 50, 100],
                    pager: "#gridpager"
                });
                /*创建jqGrid的操作按钮容器*/
                jQuery("#userList").jqGrid('navGrid', '#gridpager', {
                    edit: false,
                    add: false,
                    del: false,
                    search: false
                });
            };
            //浏览器窗口发生变化时同时变化DIV高度
            var timer = 0;
            $(function () {
                $(window).resize(function () {
                    setTimer = setTimeout(function () {
                        $("#userList").setGridWidth($('#operation-table').width() * 1 + 14);
                        $("#userList").setGridHeight($('#operation-table').height() * 1 - 88);
                        clearTimeout(timer);
                    }, 260);
                });
            });
            // 侧边栏缩小时，实时的给jqgrid的宽和高赋值
            $("#asidebarSwitch").on('click', function () {
                var time = 0;
                var set = setInterval(function () {
                    $("#userList").setGridWidth($('#operation-table').width() * 1 + 14);
                    $("#userList").setGridHeight($('#operation-table').height() * 1 - 88);
                    time++;
                    if (time == 201) {
                        clearInterval(set);
                    }
                }, time);
            });

            // zTree获取组织关系树结构
            var zTreeObj;
            var zNodes;
            // zTree 的参数配置
            var setting = {
                view: {
                    dblClickExpand: true, // 取消双击展开事件
                },
                data: {
                    simpleData: {
                        enable: true, //是否开启异步加载模式
                    }
                },
                callback: {
                    onClick: onClick
                }
            };
            // 页面加载完成获取zTree数据
            $(document).ready(getZtree());

            // zTree加载数据
            function getZtree() {
                $.ajax({
                    url: contextPath + "/Organization/queryOrganizationTree",
                    type: "get",
                    cache: false,
                    dataType: "json",
                    success: function (data) {
                        if (data.code == 2) {
                            $(".userControl-tree").html(data.message);
                            return;
                        }
                        zNodes = data;
                        zTreeObj = $.fn.zTree.init($("#organizationTree"), setting, zNodes);
                        updateType();
                    },
                    error: function (data) {
                        toastr.error("请求失败，请稍后再试!");
                    }
                });
            }

            // 点击树节点为 jqgrid 加载数据
            function onClick(e, treeId, treeNode) {
                var userId = treeNode.organizationCode;
                $("#userList").setGridParam({
                    url: contextPath + "/user/queryUserJqg",
                    postData: {
                        queryCond: {
                            username: '',
                            orgIdCondition: userId
                        }
                    },
                    page: 1
                }).trigger("reloadGrid");
            };

            function updateType() {
                var zTree = $.fn.zTree.getZTreeObj("organizationTree"),
                    nodes = zTree.transformToArray(zTree.getNodes());
                for (var i = 0, l = nodes.length; i < l; i++) {
                    var num = nodes[i].children ? nodes[i].children.length : 0;
                    if (nodes[i].children.length == 0 || num.length == undefined) {
                        nodes[i].name = nodes[i].name;
                        zTree.updateNode(nodes[i]);
                    } else {
                        nodes[i].name = nodes[i].name.replace(/ \(.*\)/gi, "") + " (" + num + ")";
                        zTree.updateNode(nodes[i]);
                    }
                }
            };

            // 搜索
            $("#searchUser").on('click', function () {
                var userName = $('#search').val();
                $("#userList").setGridParam({
                    url: contextPath + "/user/queryUserJqg",
                    postData: {
                        queryCond: {
                            username: userName,
                            orgIdCondition: ''
                        }
                    },
                    page: 1
                }).trigger("reloadGrid");

            });
            $('#search').on('keypress', function (event) {
                var theEvent = window.event || event;
                var code = theEvent.keyCode || theEvent.which;
                var userName = $('#search').val();
                var localData;
                if (code == 13) {
                    $("#userList").setGridParam({
                        url: contextPath + "/user/queryUserJqg",
                        postData: {
                            queryCond: {
                                username: userName,
                                orgIdCondition: ''
                            }
                        },
                        page: 1
                    }).trigger("reloadGrid");
                }
            });

            // 修改 删除
            var data;
            $("#userList").on('click', '.modify, .connected, .del', function () {
                var $this = $(this),
                    parentId = $(this).parent().parent().attr('id'),
                    ids = $("#userList").jqGrid('getRowData', parentId);
                delete ids.operation;
                if ($this.hasClass("modify")) {
                    $.cookie('userData', JSON.stringify(ids));
                    window.location.hash = "platform-userGroup-modifyUser";
                } else if ($this.hasClass("connected")) {
                    $.cookie('userData', JSON.stringify(ids));
                    window.location.hash = "platform-userGroup-connectedUser";
                } else if ($this.hasClass("del")) {
                    data = ids;
                }
            });
            // 点击删除
            $("#deleteData").on('click', function () {
                var id = data.id;
                $.ajax({
                    url: contextPath + '/user/delete/' + id,
                    type: "delete",
                    contentType: "application/json",
                    dataType: "json",
                    success: function (data) {
                        if (data.code == 1) {
                            $.ajax({
                                url: contextPath + '/user/deleteUserToProductLine/' + id,
                                type: "delete",
                                contentType: "application/json",
                                dataType: "json",
                                success: function (data1) {
                                    $('#deleteNotice').modal('hide');
                                    toastr.success('删除成功！');
                                    var treeNode = zTreeObj.getSelectedNodes();
                                    var userId = '';
                                    if (treeNode.length > 0) {
                                        userId = treeNode[0].organizationCode;
                                    }
                                    $("#userList").setGridParam({
                                        url: contextPath + "/user/queryUserJqg",
                                        postData: {
                                            queryCond: {
                                                username: '',
                                                orgIdCondition: userId
                                            }
                                        },
                                        page: 1
                                    }).trigger("reloadGrid");
                                },
                                error: function () {
                                    toastr.error('操作失败！');
                                }
                            });
                        } else {
                            toastr.error('删除失败！');
                        }
                    },
                    error: function () {
                        toastr.error('操作失败！');
                    }
                });
            });
        </script>
    </div>
</body>
</html>